package com.example.myhttplibrary.client;

import com.example.myhttplibrary.exceptiopn.ExceptionEngine;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.http.Header;

public class HttpObservable  {

    //Rxjava绑定生命周期
    LifecycleProvider lifecycleProvider;
    //绑定Activity具体的生命周的
    ActivityEvent activityEvent;
    //绑定Fragment的具体的生命周期的
    FragmentEvent fragmentEvent;
    //请求头信息
    Map<String, Object> headres;


    Observable observable;
    public HttpObservable(Builder builder) {
        this.lifecycleProvider=builder.lifecycleProvider;
        this.activityEvent=builder.activityEvent;
        this.fragmentEvent=builder.fragmentEvent;
        this.observable=builder.observable;
        this.headres=builder.headres;

    }

    public OkHttpClient  headers(){
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader( "Content-Type:", "text/html;charset=utf-8")
                                .addHeader("Accept-Encoding", "gzip, deflate")
                                .addHeader("Connection", "keep-alive")
                                .addHeader("Accept", "*/*")
                                .addHeader("Cookie", "add cookies here")
                                .build();
                        return chain.proceed(request);
                    }

                })
                .build();

        return httpClient;

    }



    public Observable map() {
        observable.map(new Function<JsonElement, Object>() {
            @Override
            public Object apply(JsonElement jsonElement) throws Exception {
                return new Gson().toJson(jsonElement);
            }
        });
        return observable;
    }
        public Observable onErrorResumeNext(){
            return map().onErrorResumeNext(new Function<Throwable, ObservableSource>() {
                @Override
                public ObservableSource apply(Throwable throwable) throws Exception {
                    return Observable.error(ExceptionEngine.handleException(throwable));
                }
            });
        }


        public Observable bindToLifecycle(){
            Observable observable=null;
            if (lifecycleProvider!=null){
                if (activityEvent!=null||fragmentEvent!=null){
                    if (activityEvent!=null&&fragmentEvent!=null){
                        observable=onErrorResumeNext().compose(lifecycleProvider.bindUntilEvent(activityEvent));
                    }

                    if (activityEvent!=null){
                         observable=onErrorResumeNext().compose(lifecycleProvider.bindUntilEvent(activityEvent));
                    }
                    if (fragmentEvent!=null){
                        observable=onErrorResumeNext().compose(lifecycleProvider.bindUntilEvent(fragmentEvent));
                    }else {
                        observable=onErrorResumeNext().compose(lifecycleProvider.bindToLifecycle());
                    }
                }
                observable=onErrorResumeNext();
            }
            return observable;
        }


        public Observable changeThread(){

            return bindToLifecycle().subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());

        }



    public static class Builder{
        //Rxjava绑定生命周期
        LifecycleProvider lifecycleProvider;
        //绑定Activity具体的生命周的
        ActivityEvent activityEvent;
        //绑定Fragment的具体的生命周期的
        FragmentEvent fragmentEvent;
        //请求头信息
        Map<String, Object> headres;
        Observable observable;
        public Builder(Observable observable) {
            this.observable=observable;
        }

        public Builder setLifecycleProvider(LifecycleProvider lifecycleProvider) {
            this.lifecycleProvider = lifecycleProvider;
            return this;
        }

        public Builder setActivityEvent(ActivityEvent activityEvent) {
            this.activityEvent = activityEvent;
            return this;
        }

        public Builder setFragmentEvent(FragmentEvent fragmentEvent) {
            this.fragmentEvent = fragmentEvent;
            return this;
        }

        public Builder setHeadres(Map<String, Object> headres) {
            this.headres = headres;
            return this;
        }
        public Builder addHeadres(String key,String value) {
            if (this.headres==null){
                this.headres=new HashMap<>();
            }
            this.headres.put(key,value);
            return this;
        }



        public HttpObservable build(){
            return new HttpObservable(this);
        }

    }

}


